package com.debby.test.fish;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.IBinder;

/**
 * 检查版本更新service
     * 此类描述的是：   
     * @author: wanglong
     * @version: 2012-3-20 下午5:33:24
 */
public class VersionUpdateService extends Service {
	protected HttpUtil httpUtil = new HttpUtil();
	
	public static String filename = "";
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		new QueryVersionTask().execute();
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		
	}

	
	private class QueryVersionTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			
			String result = httpUtil.get(getApplicationContext(), "http://oatest.gotoip55.com/skyservice/buyu/version.json");
			JSONObject resultjb;
			try {
				resultjb = new JSONObject(result);
			
				PackageManager pm = getApplicationContext().getPackageManager();     
				PackageInfo pi = null;
				String versionName = "";
				try {
					pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);
					versionName = pi.versionName;   
				} catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(!versionName.equals(resultjb.getString("versionname"))){
					String str = "/fishfree"+resultjb.getString("versionname")+".apk"; 
					filename = Environment.getExternalStorageDirectory() + str; 
					File temp = new File(filename);
					if(!temp.exists()){
						httpUtil.downloadImage(getApplicationContext(), "http://oatest.gotoip55.com/skyservice/buyu/fishfree.rar",filename);
					}
					result = resultjb.getString("info");
					return result;
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return null;
		}
		protected void onPostExecute(String result) {
			if(result!=null){
				Intent in = new Intent(getApplicationContext(),
	                    ConfirmUpdateActivity.class);
	            in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	            in.putExtra("info", result);
	            getApplicationContext().startActivity(in);
			}
		}
	}
	
	
	@Override
	public void onDestroy() {
		
	}

}
